﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class index : System.Web.UI.Page
    {
        // 初始化页面
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        // 登录
        protected void login(object sender, EventArgs e)
        {
            try
            {
                if (userName.Text.Trim() == "")
                {
                    lb.Text = "用户名不能为空";
                    userName.Focus();
                    return;
                }else if(passWord.Text.Trim() == ""){
                    lb.Text = "密码不能为空";
                    passWord.Focus();
                    return;
                }
                // 定义sql语句
                string sqlstr = "select userName,password from user where userName = @userName";
                DataSet ds = new DataSet();
                // 打开数据库
                DBcon.connection.Open();
                MySqlCommand cmd = new MySqlCommand(sqlstr, DBcon.connection);
                cmd.Parameters.Add(new MySqlParameter("@userName",MySqlDbType.VarChar,500));
                cmd.Parameters["@userName"].Value = userName.Text;
                MySqlDataReader sdr = cmd.ExecuteReader();
                if(!sdr.Read()) {
                    lb.Text = "用户不存在";
                    userName.Text = "";
                    passWord.Text = "";
                    userName.Focus();
                }else if(sdr["password"].ToString().Trim() == passWord.Text.Trim()){
                    // 登陆成功
                    Response.Redirect("home.aspx");
                }else{
                    lb.Text = "密码错误";
                    passWord.Text = "";
                    passWord.Focus();
                }
            }
            catch(Exception ex){
                lb.Text = "连接异常:"+ ex.Message;
                userName.Text = "";
                passWord.Text = "";
                userName.Focus();
            }
            finally{
                //关闭数据库
                DBcon.connection.Close();
            }
        }
    }
}